import os
import cv2
import numpy as np

try:
    from .cvio import cvio
except:
    from cvio import cvio

def contour2minAreaBbox(contour):
    contour = np.array(contour, dtype=np.float32)
    rotatedRect = cv2.minAreaRect(contour)
    bbox = cv2.boxPoints(rotatedRect).tolist()
    return bbox


def run_contour2minAreaBbox(src, dst='',recursive=True):
    annlist = cvio.load_ext_list(src, recursive=recursive)
    for ann in annlist:
        print(ann)
        annInfo = cvio.load_ann(ann)
        for i, shape in enumerate(annInfo['shapes']):
            shape_type = shape['shape_type']
            if shape_type != 'polygon':
                continue
            points = shape['points']
            points = contour2minAreaBbox(points)
            shape['points'][:] = points
        save = ann if dst in ('', None) else os.path.join(dst, os.path.basename(ann))
        cvio.write_ann(annInfo, save)


if __name__ == '__main__':
    src = r'G:\data\datasets\commodity\yagao\wmz_0916\bottle\train_new'
    run_contour2minAreaBbox(src)